<template>
  <ContentWrap>
    <el-button @click="backFirst">返 回</el-button>
  </ContentWrap>
  <el-tabs v-model="normal" class="box">
    <el-tab-pane  label="基本信息" name="info">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-divider content-position="left"><span class="font-size-16px">基础信息</span></el-divider>
        <el-form-item label="授权科目" prop="serviceIds">
          <el-cascader
            class="w-100%"
            v-model="formData.serviceIds"
            :options="serviceClassTree"
            :props="{ label: 'name', value: 'id', multiple: true }"
            filterable/>
        </el-form-item>
        <el-form-item label="从业时间" prop="workTime">
          <el-select v-model="formData.workTime" placeholder="请选择从业时间">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_COACH_WORK_TIME)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="授权场地" prop="venueIds">
          <el-select v-model="formData.venueIds" multiple placeholder="请选择授权场地">
            <el-option
              v-for="item in venues"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-divider content-position="left"><span class="font-size-16px">个人信息</span></el-divider>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" placeholder="请选择性别">
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-divider content-position="left"><span class="font-size-16px">个人介绍</span></el-divider>
        <el-form-item label="展示图片" prop="showImages">
          <UploadImgs :limit="9" :file-size="24" v-model="formData.showImages" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <UploadImg v-model="formData.avatar" />
        </el-form-item>
        <el-form-item label="个人简介" prop="personalProfile">
          <el-input type="textarea" :rows="6" v-model="formData.personalProfile" />
        </el-form-item>
        <el-divider content-position="left"><span class="font-size-16px">其它信息</span></el-divider>
        <el-form-item label="佣金比例" prop="commissionRate">
          <el-input-number style="width: 100%" :min="0" :max="100" v-model="formData.commissionRate" placeholder="请输入佣金比例 0-100%" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="formData.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择标签">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_COACH_TAGS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="首页推荐" prop="homeRecommend">
          <el-radio-group v-model="formData.homeRecommend">
            <el-radio :value="true">推荐</el-radio>
            <el-radio :value="false">不推荐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="true">正常</el-radio>
            <el-radio :value="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工作状态" prop="isWork">
          <el-radio-group v-model="formData.isWork">
            <el-radio :value="true">上班中</el-radio>
            <el-radio :value="false">休息中</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="总评分" prop="totalScore">
          <el-rate
            v-model="formData.totalScore"
            show-score
            text-color="#ff9900"
            score-template="{value}"/>
        </el-form-item>
        <el-divider content-position="left"><span class="font-size-16px">审核信息</span></el-divider>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-tag type="warning" v-if="formData.auditStatus === 0">待审核</el-tag>
          <el-tag type="success" v-if="formData.auditStatus === 10">审核通过</el-tag>
          <el-tag type="danger" v-if="formData.auditStatus === 20">审核拒绝</el-tag>
        </el-form-item>
        <el-form-item v-if="formData.auditStatus === 20" label="拒绝原因" prop="refuseCause">
          <span>{{ formData.refuseCause }}</span>
        </el-form-item>
        <!--    <el-form-item label="人均价格（单位分）" prop="perCapitaPrice">
              <el-input v-model="formData.perCapitaPrice" placeholder="请输入人均价格（单位分）" />
            </el-form-item>-->
      </el-form>
      <el-divider content-position="left"/>
      <el-row type="flex" class="row-bg" justify="space-around">
        <el-col :span="24" style="text-align: center">
<!--          <el-button @click="backFirst">返 回</el-button>-->
          <el-button @click="submitForm" type="primary" :disabled="formLoading">保 存</el-button>
          <el-button v-if="formData.auditStatus === 0" @click="auditCoach(10)" type="success">审核通过</el-button>
          <el-button v-if="formData.auditStatus === 0" @click="auditCoach(20)" type="danger">审核拒绝</el-button>
        </el-col>
      </el-row>
    </el-tab-pane>
    <el-tab-pane  label="资金信息" name="amount">
      <el-form
        ref="amountFormRef"
        :model="amountFormData"
        :rules="amountFormRules"
        :inline="true"
        v-loading="amountFormLoading"
      >
        <el-form-item label="余额" prop="commissionRate">
          <el-input-number style="min-width: 300px" :min="0" v-model="amountFormData.balance" placeholder="请输入余额" />
        </el-form-item>
        <el-form-item label="累计收益" prop="commissionRate">
          <el-input-number style="min-width: 300px" :min="0" v-model="amountFormData.totalEarnings" placeholder="请输入累计收益" />
        </el-form-item>
        <el-form-item prop="button">
          <el-button @click="submitAmountForm" type="primary" :disabled="amountFormLoading">保 存</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="课程方案" name="plan">
      <CoachPlan v-if="normal === 'plan'" :coachId="coachId" :venues="venues" :serviceClassTree="serviceClassTree" />
    </el-tab-pane>
    <el-tab-pane label="视频介绍" name="video">
      <CoachVideo v-if="normal === 'video'" :coachId="coachId"/>
    </el-tab-pane>
    <el-tab-pane label="证书认证" name="certificate">
      <CoachCertificate v-if="normal === 'certificate'" :coachId="coachId"/>
    </el-tab-pane>
    <el-tab-pane label="教练评论" name="comment">
      <CoachComment v-if="normal === 'comment'" :coachId="coachId"/>
    </el-tab-pane>
  </el-tabs>

</template>

<script setup lang="ts">
import {getIntDictOptions, DICT_TYPE, getBoolDictOptions, getStrDictOptions} from '@/utils/dict'
import { CoachApi, Coach } from '@/api/business/coach'
import {useTagsView} from "@/hooks/web/useTagsView";
import {UploadImg} from "@/components/UploadFile";
import { ServiceClassApi, ServiceClass } from '@/api/business/serviceclass'
import { VenueApi, Venue } from '@/api/business/venue'
import CoachPlan from '../coachplan/index.vue'
import CoachCertificate from '../coachcertificate/index.vue'
import CoachVideo from '../coachvideo/index.vue'
import CoachComment from '../coachcomment/index.vue'
import {handleTree} from "@/utils/tree";
const { closeCurrent } = useTagsView()

/** 教练信息 列表 */
defineOptions({ name: 'CoachDetail' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

let normal = ref('info')

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  userId: undefined,
  nickname: undefined,
  avatar: undefined,
  personalProfile: undefined,
  name: undefined,
  mobile: undefined,
  gender: undefined,
  workTime: undefined,
  auditStatus: undefined,
  isWork: undefined,
  totalScore: undefined,
  perCapitaPrice: undefined,
  status: undefined,
  commissionRate: undefined,
  balance: undefined,
  totalEarnings: undefined,
  serviceIds: [],
  tags: [],
  showImages: [],
  venueIds: undefined,
  homeRecommend: undefined,
})
const formRules = reactive({
  nickname: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
  avatar: [{ required: true, message: '头像不能为空', trigger: 'blur' }],
  serviceIds: [{ required: true, message: '授权科目不能为空', trigger: 'change' }],
  venueIds: [{ required: true, message: '授权场地不能为空', trigger: 'change' }],
  workTime: [{ required: true, message: '从业时间不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    nickname: undefined,
    avatar: undefined,
    personalProfile: undefined,
    name: undefined,
    mobile: undefined,
    gender: undefined,
    workTime: undefined,
    auditStatus: undefined,
    isWork: undefined,
    totalScore: undefined,
    perCapitaPrice: undefined,
    status: undefined,
    commissionRate: undefined,
    balance: undefined,
    totalEarnings: undefined,
    serviceIds: [],
    tags: [],
    showImages: [],
    venueIds: undefined,
    homeRecommend: undefined,
  }
  formRef.value?.resetFields()
}

const amountFormLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const amountFormData = ref({
  id: undefined,
  balance: undefined,
  totalEarnings: undefined,
})
const amountFormRules = reactive({
  balance: [{ required: true, message: '余额不能为空', trigger: 'blur' }],
  totalEarnings: [{ required: true, message: '累计收益不能为空', trigger: 'blur' }],
})
const amountFormRef = ref() // 表单 Ref

/** 重置表单 */
const amountResetForm = () => {
  amountFormData.value = {
    id: undefined,
    balance: undefined,
    totalEarnings: undefined,
  }
  amountFormRef.value?.resetFields()
}

const auditCoach = async (auditStatus:number) => {
  let refuseCause = ''
  if (auditStatus === 10){
    await message.confirm("确认审核通过吗？", "审核通过")
  }else {
    refuseCause = (await message.promptCustomContent("确认审核拒绝吗？", "审核拒绝", '请输入拒绝原因')).value
    if (!refuseCause){
      message.error('请填写拒绝原因')
      return
    }
  }

  try {
    await CoachApi.auditCoach({id: formData.value.id, auditStatus, refuseCause})
    message.success('审核成功')
  }finally {
    await getCoachDetail()
  }
}

const submitAmountForm = async () => {
  // 校验表单
  await amountFormRef.value.validate()
  // 提交请求
  amountFormLoading.value = true
  try {

    amountFormData.value.balance = amountFormData.value.balance * 100
    amountFormData.value.totalEarnings = amountFormData.value.totalEarnings * 100

    await CoachApi.updateCoachAmount(amountFormData.value)
    message.success(t('common.updateSuccess'))
  } finally {
    amountFormLoading.value = false
    await getCoachDetail()
  }
}


const route = useRoute() // 路由
const router = useRouter() // 路由

const backFirst = async () => {
  router.push({
    name: 'Coach'
  })
  closeCurrent(this)
}

const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Coach
    await CoachApi.updateCoach(data)
    message.success(t('common.updateSuccess'))

    getCoachDetail()
  } finally {
    formLoading.value = false
  }
}

const getCoachDetail = async () => {
  resetForm()
  amountResetForm()
  formData.value = await CoachApi.getCoach(coachId.value)

  amountFormData.value.id = formData.value.id
  amountFormData.value.balance = formData.value.balance / 100
  amountFormData.value.totalEarnings = formData.value.totalEarnings / 100
}

const venues = ref([])
const getVenueAll = async () => {
  venues.value = await VenueApi.getVenueAll()
}

const serviceClassTree = ref([])
const getServiceClassAll = async () => {
  serviceClassTree.value = []
  const data = await ServiceClassApi.getServiceClassAll()
  serviceClassTree.value = handleTree(data, 'id', 'parentId')
}


let coachId = ref()

/** 初始化 **/
onMounted(() => {
  // 如果数据 ID 不存在，显示错误提示并关闭页面
  if (!route.query.id) {
    message.error('教练 ID 不存在，无法查看教练详情')
    // 关闭当前路由，返回到数据列表页面
    router.push({ name: 'Coach' })
    return
  }

  coachId.value = route.query.id;

  getCoachDetail();
  getVenueAll();
  getServiceClassAll();
})
</script>
<style scoped>
.box{
  width: 100%;
  background: white;
  padding: 10px;
}
</style>
